<template>
  <div class="app-container">
    <div class="pic-container">

      <el-dialog
        :visible.sync="visible3"
        :before-close="handleClose2"
        :modal="true"
        title="提示"
        width="70%"
        class="dialog-confirm">
        <span>确定删除吗</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="visible3 = false">取 消</el-button>
          <el-button type="primary" @click="del(dialogItem.index)">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 列表 -->
      <waterfall
        ref="waterfall"
        :line-gap="400"
        :min-line-gap="300"
        :max-line-gap="400"
        :watch="items"
        :line="line"
      >
        <waterfall-slot
          v-for="(item, index) in items"
          :width="item.width"
          :height="item.height"
          :order="index"
          :key="item.index"
          move-class="item-move"
        >
          <el-card :class="items[index].itemCardClass" >
            <img :src="item.miniUrl" class="item-image" @click="handleOpen(index)">
            <el-row>
              <el-button type="danger" size="small" class="item-button" @click="chooseItem(index)">{{ item.itemChooseText }}</el-button>
            </el-row>
          </el-card>
        </waterfall-slot>
      </waterfall>

      <el-checkbox v-model="chooseAllItems" class="picture-choose-all" @change="chooseAll()">全选</el-checkbox>
      <el-button type="danger" icon="el-icon-delete" @click="delChoose()">删除选中</el-button>
      <el-button type="primary" icon="el-icon-download" @click="handleBatchDownload()">下载选中</el-button>
      <el-pagination
        :total="itemTotal"
        :page-size="pageSize"
        background
        class="picture-page"
        layout="prev, pager, next"
        @current-change="pageChange"
      />

      <!-- 详情页 -->
      <el-dialog
        :visible.sync="dialogItem.visible"
        :before-close="handleClose"
        :fullscreen="true"
        class="dialog"
        center
      >
        <el-card shadow="always">
          <el-card shadow="always">
            <el-button style="float: right" type="info" size="small" icon="el-icon-close" @click="handleClose">关闭详情</el-button>
            <h2>标题：{{ dialogItem.title }}</h2>
            <label>图片名: {{ dialogItem.origin_name }}</label><br><br>
            <label>作者姓名: {{ dialogItem.auth_name }}</label><br><br>
            <label>作者ID: {{ dialogItem.auth_uid }}</label><br><br>
            <label>图片说明: {{ dialogItem.comment }}</label><br><br>
            <el-button type="primary" size="small" icon="el-icon-download" @click="download(dialogItem.index)">下载</el-button>
            <el-button type="success" size="small" icon="el-icon-star-on" @click="collect(dialogItem.index)">收藏</el-button>
            <el-popover
              v-model="dialogItem.visible2"
              placement="top"
              width="160">
              <p>确定要删除</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="dialogItem.visible2 = false">取消</el-button>
                <el-button type="primary" size="mini" @click="del(dialogItem.index)">确定</el-button>
              </div>
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="small" >删除</el-button>
            </el-popover>
          </el-card>
          <br>
          <el-card shadow="always">
            <img :src="dialogItem.url" class="dialog-image">
          </el-card>
          <br>
          <br>
        </el-card>

      </el-dialog>

    </div>
  </div>
</template>

<script>
import Waterfall from 'vue-waterfall/lib/waterfall'
import WaterfallSlot from 'vue-waterfall/lib/waterfall-slot'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import { getFile } from '@/utils/other'
import { PictureFromType } from '@/defs/picture'
import { getConsiderList, feel, del, delMulti } from '@/api/picture'

export default {
  components: {
    Waterfall,
    WaterfallSlot
  },
  data() {
    return {
      filterText: '',
      currentDate: 100,
      line: 'h',
      visible3: false,
      dialogItem: {
        id: 0,
        visible: false,
        visible2: false,
        index: 0,
        title: '',
        url: '',
        miniUrl: '',
        width: 0,
        height: 0,
        auth_uid: 0,
        auth_name: 0,
        comment: 0,
        origin_name: ''
      },
      itemTotal: 100,
      chooseAllItems: false,
      nowPage: 1,
      pageSize: 5,
      items: []
    }
  },
  created() {
    this.pageChange(0)
  },
  methods: {
    // 页数改变
    pageChange(val) {
      getConsiderList({ page: val, rows: 5 }).then(response => {
        this.genItemsByResponse(response.data.list, response.data.count)
        this.nowPage = val
        console.log(this.itemTotal)
      })
    },
    // 解析接口返回的list
    genItemsByResponse(list, total) {
      this.items = []
      this.itemTotal = total
      for (let index = 0; index < list.length; index++) {
        var item = list[index]
        this.items[index] = {
          id: item.id,
          index: index,
          origin_name: item.origin_name,
          auth_name: item.auth_name,
          auth_uid: item.auth_uid,
          comment: item.comment,
          feel: item.feel,
          height: 0.25 * item.width + item.height,
          url: item.url,
          miniUrl: item.miniUrl,
          width: item.width,
          itemCardClass: 'item-card-normal',
          itemChoose: false,
          itemChooseText: '选择'
        }
      }
      this.chooseAllItems = false
    },
    // 查看详情
    handleOpen(index, target) {
      var item = this.items[index]
      this.dialogItem = {
        id: item.id,
        visible: true,
        index: index,
        title: '第' + index + '张图片',
        url: item.url,
        width: item.width,
        height: item.height,
        origin_name: item.origin_name,
        auth_name: item.auth_name,
        auth_uid: item.auth_uid,
        comment: item.comment,
        state: item.state
      }
    },
    // 关闭详情
    handleClose() {
      this.dialogItem.url = ''
      this.dialogItem.visible = false
      this.dialogItem.visible2 = false
    },
    // 详情里面的删除确认界面
    handleClose2() {
      this.visible3 = false
    },
    // 选中（取消选中）某个图片
    chooseItem(index) {
      if (this.items[index].itemCardClass === 'item-card-choose') {
        this.items[index].itemCardClass = 'item-card-normal'
        this.items[index].itemChoose = false
        this.items[index].itemChooseText = '选择'
        this.chooseAllItems = false
      } else {
        this.items[index].itemCardClass = 'item-card-choose'
        this.items[index].itemChoose = true
        this.items[index].itemChooseText = '取消选择'
        let chooseAll = true
        for (const i in this.items) {
          if (!this.items[i].itemChoose) {
            chooseAll = false
            break
          }
        }
        this.chooseAllItems = chooseAll
      }
      this.$forceUpdate()
    },
    // 选中（取消选中）所有图片
    chooseAll() {
      if (this.chooseAllItems) {
        for (const i in this.items) {
          this.items[i].itemCardClass = 'item-card-choose'
          this.items[i].itemChoose = true
          this.items[i].itemChooseText = '取消选择'
        }
      } else {
        for (const i in this.items) {
          this.items[i].itemCardClass = 'item-card-normal'
          this.items[i].itemChoose = false
          this.items[i].itemChooseText = '选择'
        }
      }
    },

    // 收藏
    collect(index) {
      feel({ type: PictureFromType.CONSIDER, feel: PictureFromType.LOVE, id: this.items[index].id }).then(response => {
        console.log(response)
        this.handleClose()
        this.handleClose2()
        this.$message({ message: '已放入收藏de图片里', type: 'success' })
        this.pageChange(this.nowPage)
      })
    },

    // 确认删除
    del(index) {
      if (this.items.length <= index) {
        this.$message({ message: '数据长度对不上了，请刷新界面', type: 'danger' })
        return
      }
      del({ type: PictureFromType.CONSIDER, id: this.items[index].id }).then(response => {
        this.handleClose()
        this.handleClose2()
        this.$message({ message: '删除成功', type: 'success' })
        this.pageChange(this.nowPage)
      })
    },

    // 批量下载
    handleBatchDownload() {
      var urls = []
      for (let index = 0; index < this.items.length; index++) {
        if (this.items[index].itemChoose) {
          urls[index] = this.items[index].url
        }
      }
      if (urls.length === 0) {
        this.$message({ message: '请先选择图片', type: 'danger' })
        return
      }
      const zip = new JSZip()
      const cache = {}
      const promises = []
      urls.forEach(item => {
        const promise = getFile(item).then(urls => { // 下载文件, 并存成ArrayBuffer对象
          const arr_name = item.split('/')
          const file_name = arr_name[arr_name.length - 1] // 获取文件名
          zip.file(file_name, urls, { binary: true }) // 逐个添加文件
          cache[file_name] = urls
        })
        promises.push(promise)
      })

      Promise.all(promises).then(() => {
        zip.generateAsync({ type: 'blob' }).then(content => { // 生成二进制流
          var date = new Date()
          var fileName = '酷我拼图(' + date.getFullYear() + '年' + date.getMonth() + '月' + date.getDate() + '日 ' + date.getHours() + '时' + date.getMinutes() + '分' + ')' + '.zip'
          FileSaver.saveAs(content, fileName) // 利用file-saver保存文件
        })
      })
    },

    // 批量删除
    delChoose() {
      var ids = []
      for (var i = 0; i < this.items.length; i++) {
        if (this.items[i].itemChoose) {
          ids[ids.length] = this.items[i].id
        }
      }
      if (ids.length === 0) {
        this.$message({ message: '请先选中图片', type: 'danger' })
        return
      }
      var idsStr = ids.join('_')
      delMulti({ type: PictureFromType.CONSIDER, ids: idsStr }).then(response => {
        this.handleClose()
        this.handleClose2()
        this.$message({ message: '批量删除成功', type: 'success' })
        this.pageChange(this.nowPage)
      })
    },

    // 下载单个
    download(index) {
      var item = this.items[index]
      var a = document.createElement('a')
      a.href = item.url
      a.download = item.title
      a.click()
    }
  }
}
</script>

<style  rel="stylesheet/scss" lang="scss">
body {
  margin: 5px;
  font-family: Helvetica, sans-serif;
}
.item {
  position: absolute;
  top: 5px;
  left: 5px;
  right: 5px;
  bottom: 5px;
  font-size: 1.2em;
  color: rgb(0, 158, 107);
}
.item:after {
  content: attr(index);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}
.wf-transition {
  transition: opacity 0.3s ease;
  -webkit-transition: opacity 0.3s ease;
}
.wf-enter {
  opacity: 0;
}
.item-move {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
  -webkit-transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}
.item-card-normal {
  margin-left: 2px;
  height: 90%;
}
.item-card-choose{
  margin-left: 2px;
  height: 90%;
  background-color: rgb(216, 220, 230);
}
.item-image {
  width: 100%;
}
.item-tag{
  width: 100%;
  display: block;
  text-align: center;
}
.item-button {
  display: block;
  float: right;
  margin-top: 2%;
  width: 100%;
}
.dialog-image {
  margin: 0, auto;
  max-width: 80%;
  max-height: 50%;
}
.picture-choose-all{
  margin-right: 2%;
}
.picture-page{
  float: right;
}
</style>
